package com.knight.security.browser;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * 自定义获取用户信息的Service
 *
 * @author knight
 */
@Component
public class MyUserDetailsService implements UserDetailsService {
    private static final Logger LOGGER = LoggerFactory.getLogger(MyUserDetailsService.class);

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 通过登陆的用户从数据库或其他存储介质中获取用户信息
     *
     * @param username 用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LOGGER.info("username:{}", username);
        // 根据用户名查询数据获取用户信息
        String DBUsername = username;
        // 因为是从数据库中获取的，那肯定是已经加密好的。这里模拟数据库中已经加密好的数据
        String DBPassword = passwordEncoder.encode("1234");
        LOGGER.info("password:{}", DBPassword);
        //登陆账号是否可用
        boolean enabled = true;
        //账号是否过期
        boolean accountNonExpired = true;
        //password是否过期
        boolean credentialsNonExpired = true;
        // 账号是否锁定
        boolean accountNonLocked = true;
        return new User(DBUsername, DBPassword, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked,
                AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }
}
